//
//  SZTTabbar.m
//  OC-微博
//
//  Created by z先生 on 17/2/7.
//  Copyright © 2017年 SZT. All rights reserved.
//

#import "SZTTabbar.h"
#import "SZTTabBarButton.h"

@interface SZTTabbar()

@property(nonatomic,weak)SZTTabBarButton * selectedButton;

@end

@implementation SZTTabbar

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
            }
    
    return self;
}

-(void)addTabbarButtonWithItem:(UITabBarItem *)item{
   
    SZTTabBarButton * button = [[SZTTabBarButton alloc]init];
    
    [self addSubview:button];
    
//    [button setTitle:item.title forState:UIControlStateNormal];
//    
//    [button setImage:item.image forState:UIControlStateNormal];
//    
//    [button setImage:item.selectedImage forState:UIControlStateSelected];
    
    button.item = item;
    
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.subviews.count == 1) {
        
        [self buttonClick:button];
        
    }
    
}

-(void)buttonClick:(SZTTabBarButton *)button{
    
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedButtonFrom:to:)]) {
        
        [self.delegate tabBar:self didSelectedButtonFrom:self.selectedButton.tag to:button.tag];
        
    }
    
    //
    self.selectedButton.selected = NO;
    
    button.selected = YES;
    
    self.selectedButton = button;
    
    
}
-(void)layoutSubviews{
    
    [super layoutSubviews];
    
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width/self.subviews.count;
    CGFloat buttonH = self.frame.size.height;
    
    for (int index = 0; index<self.subviews.count; index++) {
        
        SZTTabBarButton * button = self.subviews[index];
        
        CGFloat buttonX = index * buttonW;
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        button.tag = index;
    }
}
@end
